<script setup name="ShopCalendar">
import Calendar from './components/calendar'
import TableForm from './components/table'
import {
  GetListAPI,
  GetshopCalendarAPI,
  DelDataAPI,
  EditDataAPI,
  AddDataAPI,
} from '@/api/schedule/scheduleConfig/shopCalendar'

const { proxy } = getCurrentInstance()
/**
 * 表单
 */
const ruleFormRef = ref(null)
/**
 * 表单
 */
const TableFormRef = ref(null)
/**
 * 日历查看ref
 */
const calendarRef = ref(null)
// 封装 方法 字典查询

// 新增弹窗
const addIsShow = ref(false)

// 标题
const title = ref('新增')

// 保存加载状态
const Btnloading = ref(false)

// 表格加载状态
const loading = ref(false)

// 表格数据
const TableData = ref([])

// 列表总数量
const total = ref(0)

// 是否禁用删除
const DelDisabled = ref(false)

// 是否禁用 单选
const ExamineDisabled = ref(false)

// 树结构
const treeData = ref([])

// 选中的树结构
const treeRow = ref({})

// 按钮加载
const BtnLoading = ref(false)

// 是否禁用表单输入
const disabled = ref(false)

/**
 * 选择的id
 */
const Ids = ref([])
/**
 * 选择的数据
 */
const rows = ref([])

/**
 * tabs
 */
const editableTabsValue = ref('工厂日历')
// 查询条件
const selectList = ref([
  { type: '日期范围' },
  { label: '日历编码', model: 'calendarCode', type: '输入框' },
  { label: '日历名称', model: 'calendarName', type: '输入框' },
])

// 查询条件
const query = reactive({
  pageNum: 1,
  pageSize: 10,
})

// 新增字段modeling
const ruleForm = reactive({
  calendarName: '', // 日历名称
  calendarCode: '', // 日历编码
  calendarStartTime: '', // 开始时间
  calendarEndTime: '', // 结束时间
  calendarSaturdayWork: '', // 周六上班 1上 2不上
  calendarWeekendWork: '', // 周天上班 1上 2不上
  calendarHolidayWork: '', // 节假日上班 1上 2不上
  calendarJson: {
    teamCode: [],
    restCode: [],
    lineCode: [],
  },
})

// 表单校验
const rules = reactive({
  calendarName: [
    { required: true, message: '请填写日历名称', trigger: 'blur' },
  ],
  calendarCode: [
    { required: true, message: '请填写日历编码', trigger: 'bulr' },
    { validator: proxy.alphabet, trigger: 'blur' },
  ],
  calendarStartTime: [
    { required: true, message: '请填写开始时间', trigger: 'blur' },
  ],
  calendarEndTime: [
    { required: true, message: '请填写结束时间', trigger: 'blur' },
  ],
})

/**
 * 弹窗 SAT------------------
 */

// 新增弹窗
const add = () => {
  title.value = '新增'
  addIsShow.value = true
  console.log('-----------')
}

// 修改弹窗
const edit = async (val) => {
  try {
    proxy.$modal.loading('请稍候...')
    title.value = '修改'
    const { data: res } = await GetshopCalendarAPI(val)
    for (let Key in res) {
      ruleForm[Key] = res[Key]
    }
    addIsShow.value = true
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}

// 查看弹窗
const dxamine = async (val) => {
  try {
    proxy.$modal.loading('请稍候...')
    title.value = '查看'
    const { data: res } = await GetshopCalendarAPI(val)
    for (let Key in res) {
      ruleForm[Key] = res[Key]
    }
    addIsShow.value = true
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}

/**
 * 弹窗 END------------------
 */

const getDateNum = (date) => {
  return Date.parse(date)
}

// 新增提交
const addSub = async () => {
  ruleFormRef.value.validate(async (valid, fields) => {
    if (!valid) return
    try {
      console.log('====')
      BtnLoading.value = true
      const obj = TableFormRef.value.Submit()
      console.log('obj', obj)
      const isif = obj.teamCode.every(
        (item) =>
          item.teamInfo ||
          item.teamPeriod ||
          item.teamStartTime ||
          item.teamEndTime
      )
      const lineIsif = obj.lineCodeDto.every((item) => item.shopId)

      if (!isif) return proxy.warningMsg('班别信息请填写完整')
      if (!lineIsif) return proxy.warningMsg('线别设置请填写完整')
      const isin = obj.teamCode.every(
        (item) =>
          getDateNum(`2023-01-01 ${item.teamStartTime}`) <
          getDateNum(`2023-01-01 ${item.teamEndTime}`)
      )
      if (!isin && item.teamTranssky == 2)
        return proxy.warningMsg(
          '结束时间小于开始时间,且跨天标识未开启，不允许保存'
        )
      obj.lineCodeDto?.map((t) => {
        t.shopId = t.shopId?.join(',')
      })

      ruleForm.calendarJson = JSON.stringify(obj)
      obj.lineCodeDto?.map((t) => {
        t.shopId = t.shopId?.split(',')
      })
      await AddDataAPI(ruleForm)
      getList()
      close()
      proxy.successMsg('新增成功')
    } catch {
    } finally {
      // BtnLoading.value = false
    }
  })
}

// 修改提交
const editSub = () => {
  ruleFormRef.value.validate(async (valid, fields) => {
    if (!valid) return
    try {
      BtnLoading.value = true
      const obj = TableFormRef.value.Submit()
      const isif = obj.teamCode.every(
        (item) =>
          item.teamInfo ||
          item.teamPeriod ||
          item.teamStartTime ||
          item.teamEndTime
      )
      const lineIsif = obj.lineCodeDto.every((item) => item.shopId)
      if (!isif) return proxy.warningMsg('班别信息请填写完整')
      if (!lineIsif) return proxy.warningMsg('线别设置请填写完整')
      const isin = obj.teamCode.every(
        (item) =>
          getDateNum(`2023-01-01 ${item.teamStartTime}`) <
          getDateNum(`2023-01-01 ${item.teamEndTime}`)
      )
      if (!isin && item.teamTranssky == 2)
        return proxy.warningMsg(
          '结束时间小于开始时间,且跨天标识未开启，不允许保存'
        )
      obj.lineCodeDto?.map((t) => {
        t.shopId = t.shopId?.join(',')
      })

      ruleForm.calendarJson = JSON.stringify(obj)
      obj.lineCodeDto?.map((t) => {
        t.shopId = t.shopId?.split(',')
      })
      await EditDataAPI(ruleForm)

      getList()
      close()
      proxy.successMsg('修改成功')
    } catch {
    } finally {
      BtnLoading.value = false
    }
  })
}

// 删除
const del = async (val) => {
  const MesBox = await proxy.DelMessageBox()
  if (!MesBox) return
  const res = await DelDataAPI(
    Ids.value.length <= 0 ? val : Ids.value.join(',')
  )
  if (res.code !== 200) return (BtnLoading.value = false)
  getList()
  proxy.successMsg('删除成功')
}

// 弹窗关闭时
const close = () => {
  console.log('-----------------')

  addIsShow.value = false
  for (let Key in ruleForm) {
    ruleForm[Key] = ''
  }
  ruleForm.calendarJson = {
    teamCode: [],
    restCode: [],
    lineCode: [],
  }
}

// 列表选中 及 判断是否禁用删除 || 修改
const handleSelectionChange = (selection) => {
  rows.value = selection
  Ids.value = selection.map((item) => item.calendarId)
  DelDisabled.value = !selection?.length
  selection?.length <= 0 || selection?.length > 1
    ? (ExamineDisabled.value = true)
    : (ExamineDisabled.value = false)
}
handleSelectionChange([])

// 查询
const selectSubmit = (obj) => {
  for (let key in obj) {
    query[key] = obj[key]
  }
  getList()
}

// 获取列表
const getList = async () => {
  try {
    const res = await GetListAPI(query)
    if (res.code !== 200) return
    TableData.value = res.rows
    loading.value = false
  } catch {
  } finally {
    loading.value = false
  }
}
getList()

/**
 * tab切换
 */
const tabChange = (v) => {
  if (v == '日历查看') calendarRef.value.getCalendar()
}
</script>

<template>
  <div class="app-container">
    <!-- 查询条件组件 -->
    <p-select-form :selectForm="selectList" @selectSubmit="selectSubmit" />
    <el-card>
      <div class="mb10">
        <el-button
          type="primary"
          v-hasPermi="['system:shopCalendar:add']"
          @click="add"
          >新增</el-button
        >
        <el-button
          type="danger"
          v-hasPermi="['system:shopCalendar:remove']"
          :disabled="DelDisabled"
          @click="del"
          >批量删除</el-button
        >
      </div>
      <el-tabs
        type="border-card"
        @tab-change="tabChange"
        v-model="editableTabsValue"
      >
        <el-tab-pane label="工厂日历" name="工厂日历">
          <!-- 表格数据 -->
          <el-table
            v-loading="loading"
            stripe
            border
            :data="TableData"
            style="margin-top: 10px"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              type="selection"
              width="55"
              align="center"
              fixed="left"
            />
            <el-table-column
              label="序号"
              width="70"
              type="index"
              align="center"
            />
            <el-table-column
              label="日历编码"
              prop="calendarCode"
              width="auto"
              align="center"
            />
            <el-table-column
              label="日历名称"
              prop="calendarName"
              width="auto"
              align="center"
            />
            <el-table-column
              label="开始时间"
              prop="calendarStartTime"
              width="150"
              align="center"
            />
            <el-table-column
              label="结束时间"
              prop="calendarEndTime"
              width="150"
              align="center"
            />
            <el-table-column label="周六上班" width="auto" align="center">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.calendarSaturdayWork"
                  :active-value="0"
                  disabled
                  :inactive-value="1"
                />
                <!-- <p-switch disabled v-model="scope.row.calendarSaturdayWork" /> -->
              </template>
            </el-table-column>
            <el-table-column label="周天上班" width="auto" align="center">
              <template #default="scope">
                <!-- <p-switch disabled v-model="scope.row.calendarWeekendWork" /> -->
                <el-switch
                  v-model="scope.row.calendarWeekendWork"
                  :active-value="0"
                  disabled
                  :inactive-value="1"
                />
              </template>
            </el-table-column>
            <el-table-column label="节假日上班" width="150" align="center">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.calendarHolidayWork"
                  :active-value="0"
                  disabled
                  :inactive-value="1"
                />
                <!-- <p-switch disabled v-model="scope.row.calendarHolidayWork" /> -->
              </template>
            </el-table-column>
            <!-- <el-table-column label="线别" prop="calendarLine" width="auto" align="center" /> -->
            <el-table-column
              label="操作"
              align="center"
              width="160"
              fixed="right"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <div>
                  <el-link
                    v-hasPermi="['system:shopCalendar:edit']"
                    type="primary"
                    text="修改"
                    @click="edit(scope.row.calendarId)"
                  />
                  <el-link
                    v-hasPermi="['system:shopCalendar:remove']"
                    text="删除"
                    type="danger"
                    @click="del(scope.row.calendarId)"
                  />

                  <el-link
                    type="primary"
                    v-hasPermi="['system:shopCalendar:query']"
                    text="查看"
                    @click="dxamine(scope.row.calendarId)"
                  />
                </div>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="query.pageNum"
            v-model:limit="query.pageSize"
            @pagination="getList"
          />
        </el-tab-pane>
        <el-tab-pane label="日历查看" name="日历查看">
          <Calendar ref="calendarRef" />
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 新增弹窗 -->
    <p-dialog
      v-model="addIsShow"
      :title="title"
      @close="close"
      @ok="title == '新增' ? addSub() : editSub()"
      width="70%"
    >
      <template #body>
        <div class="formBox">
          <div class="ruleFormClass">
            <el-form
              inline
              scroll-to-error
              ref="ruleFormRef"
              :model="ruleForm"
              :rules="rules"
              label-width="100px"
              label-position="right"
              status-icon
            >
              <el-form-item label="日历编码" prop="calendarCode">
                <el-input
                  clearable
                  :disabled="title == '查看' || title == '修改'"
                  v-model="ruleForm.calendarCode"
                  placeholder="请填写日历编码"
                />
              </el-form-item>
              <el-form-item label="日历名称" prop="calendarName">
                <el-input
                  clearable
                  :disabled="title == '查看'"
                  v-model="ruleForm.calendarName"
                  placeholder="请填写日历名称"
                />
              </el-form-item>
              <el-form-item label="开始时间" prop="calendarStartTime">
                <el-date-picker
                  value-format="YYYY-MM-DD"
                  :disabled="title == '查看'"
                  v-model="ruleForm.calendarStartTime"
                  arrow-control
                  placeholder="开始时间"
                />
              </el-form-item>
              <el-form-item label="结束时间" prop="calendarEndTime">
                <el-date-picker
                  value-format="YYYY-MM-DD"
                  :disabled="title == '查看'"
                  v-model="ruleForm.calendarEndTime"
                  arrow-control
                  placeholder="结束时间"
                />
              </el-form-item>
            </el-form>
          </div>
          <div class="flex05">
            <div class="flex">
              <div class="switch">
                <label>周六上班</label>
                <!-- <p-switch
                  :disabled="title == '查看'"
                  v-model="ruleForm.calendarSaturdayWork"
                /> -->
                <el-switch
                  v-model="ruleForm.calendarSaturdayWork"
                  :active-value="0"
                  :inactive-value="1"
                  :disabled="title == '查看'"
                />
              </div>
              <div class="switch">
                <label>周天上班</label>
                <!-- <p-switch
                  :disabled="title == '查看'"
                  v-model="ruleForm.calendarWeekendWork"
                /> -->
                <el-switch
                  v-model="ruleForm.calendarWeekendWork"
                  :active-value="0"
                  :disabled="title == '查看'"
                  :inactive-value="1"
                />
              </div>
            </div>
            <div class="switch mt20">
              <label>节假日上班</label>

              <el-switch
                v-model="ruleForm.calendarHolidayWork"
                :active-value="0"
                :disabled="title == '查看'"
                :inactive-value="1"
              />
            </div>
          </div>
        </div>
        <!-- 表格表单 -->
        <div class="table">
          <TableForm
            :data="ruleForm.calendarJson"
            :disabled="title == '查看'"
            ref="TableFormRef"
          />
        </div>

        <!-- 按钮 -->
        <!-- <Btn
          v-if="title != '查看'"
          :loading="BtnLoading"
          @submit="title == '新增' ? addSub() : editSub()"
          @close="close"
        /> -->
      </template>
    </p-dialog>
  </div>
</template>

<style lang="scss" scoped>
.is-selected {
  color: #061626;
}
.switch {
  margin-left: 20px;
  display: flex;
  align-items: center;
  label {
    text-align: right;
    display: inline;
    width: 80px !important;
    margin-right: 10px;
  }
}
.formBox {
  display: flex;
  justify-content: space-around;
  .ruleFormClass {
    flex: 1.5;
  }
}
</style>
